/****************************************************
	文件：EdgeDetectionV2.cs
	作者：HuskyT
	邮箱：1005240602@qq.com
	日期：2020/8/19 17:48:18
	功能：基于深度、法线纹理 的边缘检测
*****************************************************/

using System;
using UnityEngine;

namespace RenderingPractice
{
    public class EdgeDetectionV2 : PostEffectsBase
    {
        public Shader EdgeDetectShader;
        private Material mEdgeDetectMat;
        public Material EdgeDetectMat
        {
            get
            {
                mEdgeDetectMat = CheckShaderAndCreateMaterial(EdgeDetectShader, mEdgeDetectMat);
                return mEdgeDetectMat;
            }
        }

        [Range(0.0f, 1.0f), Tooltip("仅有边缘颜色，其他为背景色")]
        public float EdgeOnly = 0.0f;
        [Tooltip("边缘颜色")]
        public Color EdgeColor = Color.black;
        [Tooltip("背景颜色")]
        public Color BackgroundColor = Color.white;
        [Range(0.45f, 1.55f), Tooltip("采样距离（描边宽度）")]
        public float SampleDis = 1.0f;
        [Range(0.0f, 3.0f), Tooltip("法线值敏感度")]
        public float SensitivityNormal = 1.0f;
        [Range(0.0f, 3.0f), Tooltip("深度值敏感度")]
        public float SensitivityDepth = 1.0f;

        private void OnEnable()
        {
            GetComponent<Camera>().depthTextureMode |= DepthTextureMode.DepthNormals;
        }

        [ImageEffectOpaque] //不对透明物体描边
        private void OnRenderImage(RenderTexture source, RenderTexture destination)
        {
            if (EdgeDetectMat != null)
            {
                EdgeDetectMat.SetFloat("_EdgeOnly", EdgeOnly);
                EdgeDetectMat.SetColor("_EdgeColor", EdgeColor);
                EdgeDetectMat.SetColor("_BackgroundColor", BackgroundColor);
                EdgeDetectMat.SetFloat("_SampleDis", SampleDis);
                EdgeDetectMat.SetVector("_Sensitivity", new Vector4(SensitivityNormal, SensitivityDepth, 0.0f, 0.0f));

                Graphics.Blit(source, destination, EdgeDetectMat);
            }
            else
            {
                Graphics.Blit(source, destination);
            }
        }
    }
}
